from utils.electrode_ctrl import ElectrodeCtrl
import numpy as np
from time import sleep, perf_counter
from utils import pressure_recv_svr

def sleep_us(us: float):
    sleep(us / 1_000_000)

# Function to busy-wait for a specified number of microseconds
def busy_wait_us(us: float):
    end_time = perf_counter() + us / 1_000_000  # Calculate end time in seconds
    while perf_counter() < end_time:
        pass  # Busy-wait loop

def rec_avg_pressure():

    previous_pressure_g = 0.0
    pressure_data = []
    start_time = None   # Record the start time of the program

    while True:
        sleep(0.01)
        #current_time = perf_counter()
        pressure_g = pressure_recv_svr.global_data
        d_N = pressure_g - previous_pressure_g
        #previous_pressure_g = pressure_g

        if pressure_g > 30 and start_time == None:
            start_time = perf_counter()
            print("Pressure exceeded 30, starting measurement.")

        if start_time != None:
            current_time = perf_counter()
            if (current_time - start_time) < 5:
                print(f'Detected Pressure: {pressure_g}')

            # 记录程序开始后5-15秒的压力数据
            if 5 <= (current_time - start_time) <= 15:
                pressure_data.append(pressure_g)
                print(f'Detected Pressure: {pressure_g}')

            # 15秒后计算平均值并停止记录
            if current_time - start_time > 15:
                if pressure_data:
                    average_pressure = np.mean(pressure_data)
                    print(f'Average pressure between 5 and 15 seconds: {average_pressure}')
                #print(f'Detected Pressure: {pressure_g}')
                
                pressure_data = []  # Reset pressure data list
                break

if __name__ == '__main__':
    frame_open = np.zeros((8, 8))
    board_s = [ElectrodeCtrl('COM9', 115200, 'com')]
    board_s += [ElectrodeCtrl('COM10', 115200, 'com')]
    pattern = np.zeros((8, 8))

    # 电压和阈值设定
    N_threshold = 350  # 压力传感器阈值
    PW_min = 200  # 小脉冲宽度，对应小电压感知
    PW_max = 800  # 大脉冲宽度，对应大电压感知
    PW = PW_min
    PP_min=1000  #长脉冲周期，小脉冲频率，对应小电压感知
    PP_max=700  #短脉冲周期，大脉冲频率，对应大电压感知
    PP=PP_min
    previous_pressure_g = 0.0

    # 启动压力传感器服务器
    pressure_recv_svr.start_pressure_recv_svr()

    pressure_data = []
    start_time = None   # Record the start time of the program

    while True:
        pressure_g = pressure_recv_svr.global_data
        d_N = pressure_g - previous_pressure_g
        previous_pressure_g = pressure_g


                # 根据压力传感器的数值调整脉冲宽度
        if pressure_g < N_threshold:
            if d_N > 0:
                PW = PW_min
                PP = PP_min
            elif d_N < 0:
                PW = PW_max
                PP = PP_max
        else:
            PW = 0  # 设置为0可能表示无刺激，这取决于具体实现

            
        if pressure_g > 30 and start_time == None:
            start_time = perf_counter()
            print("Pressure exceeded 30, starting measurement.")
                    
   

        if start_time != None:
            current_time = perf_counter()
            
            
            # 扫描电极的逻辑
            for column in range(8):
                count = 0
                #print(f'第{column + 1}列，开始扫描，持续1s')
                start_time = perf_counter()  # Record the start time using perf_counter
                while perf_counter() - start_time < 0.07:  # 持续1秒钟
                    # 单点，从左扫到右
                    for i in range(8):
                        pattern[column, i] = 1
                        # print(pattern)
                        for board in board_s:     
                            board.on()
                            board.set_tick(pattern=pattern,
                                        pp=PP,
                                        pw=PW,  # 使用动态脉冲宽度
                                        pn=1,
                                        bp=1000,
                                        pulse_type='neg'
                                        )

                            tick_start_time = perf_counter()
                            busy_wait_us(1000)  # Busy-wait for 10 microseconds
                            tick_end_time = perf_counter()
                            board.off()

                        pattern.fill(0)

                        # print(f"Tick duration: {tick_duration}")

                    count += 1
                    #print(f'第{column + 1}行 第{i + 1}列 扫描完毕')
                    #print(f'第{column + 1}行 第{i + 1}列 扫描次数：{count}')


            if (current_time - start_time) < 5:
                print(f'Detected Pressure: {pressure_g}, Pulse Width: {PW}')

            # 记录程序开始后5-15秒的压力数据
            if 5 <= (current_time - start_time) <= 15:
                pressure_data.append(pressure_g)
                print(f'Detected Pressure: {pressure_g},, Pulse Width: {PW}')

            # 15秒后计算平均值并停止记录
            if current_time - start_time > 15:
                if pressure_data:
                    average_pressure = np.mean(pressure_data)
                    print(f'Average pressure between 5 and 15 seconds: {average_pressure}')
                #print(f'Detected Pressure: {pressure_g}')
                
                pressure_data = []  # Reset pressure data list





